<template>
  <div class="register-container">
    <h2>用户注册</h2>
    <div class="register-content">
      <div class="register-form-wrapper">
        <a-form 
          ref="registerForm" 
          :model="form" 
          :rules="rules" 
          class="register-form"
        >
      <a-form-item name="avatar">
        <div class="avatar-container">
          <div class="avatar-preview" 
               @mouseenter="showAvatarPopup = true" 
               @mouseleave="handleAvatarLeave">
            <a-avatar :src="form.avatar" :size="64"></a-avatar>
            <div v-if="showAvatarPopup" 
                 class="avatar-popup"
                 @mouseenter="showAvatarPopup = true"
                 @mouseleave="showAvatarPopup = false">
              <div v-if="loadingAvatars" class="loading-avatars">
                <a-spin />
              </div>
              <div v-else class="default-options">
                <a-avatar 
                  v-for="(avatar, index) in userStore.defaultAvatars" 
                  :key="index"
                  :src="avatar" 
                  :size="64"
                  @click="selectDefaultAvatar(index)"
                  :class="{ selected: form.useDefaultAvatar && form.avatarFilename === index }"
                ></a-avatar>
              </div>
            </div>
          </div>
          <div class="upload-option">
            <input 
              type="file" 
              ref="fileInput"
              accept="image/*"
              @change="handleFileChange"
              style="display: none"
            >
            <a-button 
              type="link" 
              @click="$refs.fileInput.click()"
            >
              上传自定义头像
            </a-button>
          </div>
        </div>
      </a-form-item>

      <a-form-item name="email">
        <a-input 
          v-model:value="form.email" 
          placeholder="邮箱"
          class="form-input"
          @blur="handleEmailBlur"
        ></a-input>
      </a-form-item>

      <a-form-item name="username">
        <a-input 
          v-model:value="form.username" 
          placeholder="用户名"
          class="form-input"
        ></a-input>
      </a-form-item>

      <a-form-item name="password">
        <a-input-password 
          v-model:value="form.password" 
          placeholder="密码"
          class="form-input"
        ></a-input-password>
      </a-form-item>

      <a-form-item name="code">
        <div class="code-input-group">
          <a-input 
            v-model:value="form.code" 
            placeholder="验证码"
            class="form-input code-input"
          ></a-input>
          <a-button 
            :disabled="!canSendCode || countdown > 0"
            @click="sendVerificationCode"
            class="get-code-btn"
          >
            {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
          </a-button>
        </div>
      </a-form-item>

      <a-form-item>
        <div class="action-buttons">
          <a-button 
            type="primary" 
            @click="handleRegister"
            :loading="registerLoading"
            :disabled="!form.code"
            class="submit-btn"
          >
            注册
          </a-button>
          <a-button 
            @click="$router.push('/login')"
            class="switch-btn"
          >
            已有账号，去登录
          </a-button>
        </div>
      </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>


<script>
import { useUserStore } from '@/stores/user';

export default {
  name: 'RegisterView',
  setup() {
    const userStore = useUserStore();
    return { userStore };
  },
  data() {
    return {
      form: {
        email: '',
        username: '',
        password: '',
        avatar: null,
        code: '',
        code_id: '',
        useDefaultAvatar: true,
        avatarFilename: 0
      },
      rules: {
        // 验证规则保持不变
      },
      avatarData: null,
      countdown: 0,
      canSendCode: false,
      registerLoading: false,
      showAvatarPopup: false,
      loadingAvatars: false
    };
  },
  async created() {
    try {
      this.loadingAvatars = true;
      await this.userStore.fetchDefaultAvatars();
      // 确保defaultAvatars已加载且有数据
      if (this.userStore.defaultAvatars?.length > 0) {
        this.selectDefaultAvatar(0); // 默认选择第一个头像
      } else {
        console.warn('默认头像加载失败，使用空头像');
        this.form.avatar = '';
      }
    } catch (error) {
      console.error('初始化头像失败:', error);
    } finally {
      this.loadingAvatars = false;
    }
  },
  methods: {
    selectDefaultAvatar(index) {
      try {
        if (!this.userStore?.defaultAvatars || !Array.isArray(this.userStore.defaultAvatars)) {
          console.error('defaultAvatars未正确初始化');
          return;
        }
        const avatar = this.userStore.defaultAvatars[index];
        if (avatar) {
          this.form.avatar = avatar;
          this.form.useDefaultAvatar = true;
          this.form.avatarFilename = index;
          this.showAvatarPopup = false;
        } else {
          console.warn(`头像索引${index}不存在`);
          this.form.avatar = '';
        }
      } catch (error) {
        console.error('选择头像失败:', error);
        this.form.avatar = '';
      }
    },
    handleEmailBlur() {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      this.canSendCode = emailRegex.test(this.form.email);
    },
    async sendVerificationCode() {
      try {
        const success = await this.userStore.sendVerificationCode(this.form.email);
        if (success) {
          this.$message.success('验证码发送成功');
        //   this.form.code_id = code_id;
          this.startCountdown();
        } else {
          this.$message.error('验证码发送失败');
        }
      } catch (error) {
        this.$message.error(error || '验证码发送失败');
      }
    },
    startCountdown() {
      this.countdown = 30;
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    handleFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;
      
      if (!file.type.match('image.*')) {
        this.$message.error('请选择图片文件');
        return;
      }

      let reader = new FileReader();
      reader.onload = (event) => {
        this.form.avatar = event.target.result;
        this.form.useDefaultAvatar = false;
        this.form.avatarFilename = '';
      };
      reader.readAsDataURL(file);
      reader = new FileReader();
      reader.onload = (event) => {
        this.avatarData = event.target.result;
      };
      reader.readAsArrayBuffer(file);
    },

    handleAvatarLeave() {
      setTimeout(() => {
        if (!this.$el.querySelector('.avatar-popup:hover')) {
          this.showAvatarPopup = false;
        }
      }, 100);
    },
    
    async handleRegister() {
      try {
        await this.$refs.registerForm.validate();
        let avatar_ = this.form.avatar;
        if (this.form.useDefaultAvatar == false) {
          avatar_ = this.avatarData;
        }
        this.registerLoading = true;
        const { success, message } = await this.userStore.registerUser({
          email: this.form.email,
          username: this.form.username,
          password: this.form.password,
          avatar: avatar_,
          code: this.form.code
        });

        if (success) {
          this.$message.success(message);
          this.$router.push('/login');
        } else {
          this.$message.error(message);
        }
      } catch (error) {
        console.error('注册异常：', error);
        if (error.errorFields) {
          // 表单验证错误
          this.$message.error('请正确填写表单');
        } else {
          // 注册请求错误

          this.$message.error(error.message || '注册失败');
        }
      } finally {
        this.registerLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.register-container {
  width: 50%;
  margin: 30px auto;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  min-height: 400px;
}

.register-container h2 {
  margin: 20px 0;
  font-size: 24px;
  text-align: center;
}

.register-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  padding: 20px 0 100px;
  width: 70%;
  margin: 0 auto;
}

.register-form-wrapper {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.register-form {
  margin-top: 0;
}

.form-input {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin: 20px 0;
}

.action-buttons .ant-btn {
  flex: 1;
  height: 40px;
}

.submit-btn {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.code-input-group {
  display: flex;
}

.code-input {
  flex: 1;
  height: 40px;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  border-right: none;
}

.get-code-btn {
  width: 120px;
  height: 40px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border: 1px solid #d9d9d9;
  border-left: none;
  margin-left: -1px;
}

.avatar-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-preview {
  display: inline-block;
  cursor: pointer;
  position: relative;
}

.avatar-popup {
  position: absolute;
  bottom: 100%;
  left: 0;
  z-index: 1;
  background: white;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  margin-bottom: 8px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.default-options {
  display: flex;
  gap: 16px;
}

.upload-option {
  text-align: left;
  margin-top: 10px;
}

.selected {
  border: 2px solid #1890ff;
  border-radius: 50%;
}
</style>
